package com.dotstone.chipism.ui.security.me;


import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.ui.security.ActivityDemo;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.lib.funsdk.support.FunError;
import com.lib.funsdk.support.FunSupport;
import com.lib.funsdk.support.OnFunDeviceListener;
import com.lib.funsdk.support.OnFunDeviceOptListener;
import com.lib.funsdk.support.models.FunDevice;
import com.lib.funsdk.support.models.FunLoginType;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Demo: 搜索显示同一个局域网内的设备列表
 * 1. 切换访问模式为本地访问  - FunSDK.SysInitLocal()
 * 2. 注册设备列表更新监听  - FunSupport.registerOnFunDeviceListener()
 * 3. 搜索局域网内的设备 - FunSDK.DevSearchDevice()
 * 4. 搜索结果通过监听返回  - onLanDeviceListChanged()/标识设备列表变化了,界面可以刷新了
 * 5. 退出并注销监听
 */
public class ActivityGuideDeviceListLan extends ActivityDemo implements OnClickListener, OnFunDeviceListener ,OnFunDeviceOptListener {


    private TextView mTextTitle = null;
    private ImageButton mBtnBack = null;

    private ImageButton mBtnRefresh = null;

    private ListView mListView = null;
    private List<FunDevice> mLanDeviceList = new ArrayList<FunDevice>();


    private final int MESSAGE_REFRESH_DEVICE_STATUS = 0x100;

    private MyLanCameraAdapter cameraAdapter ;

    private boolean isAddingDevice = false;//是否添加设备中

    private FunDevice mFunDevice = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_device_security_camera_lan_list);

        mTextTitle = (TextView) findViewById(R.id.textViewInTopLayout);
        mTextTitle.setText(R.string.device_list_lan);

        mBtnBack = (ImageButton) findViewById(R.id.backBtnInTopLayout);
        mBtnBack.setOnClickListener(this);

        View layoutRefresh = setNavagateRightButton(R.layout.imagebutton_refresh);
        mBtnRefresh = (ImageButton) layoutRefresh.findViewById(R.id.btnRefresh);
        mBtnRefresh.setOnClickListener(this);

        mListView = (ListView) findViewById(R.id.listViewDevice);
        cameraAdapter = new MyLanCameraAdapter(getApplicationContext() , mLanDeviceList);
        mListView.setAdapter(cameraAdapter);





        // 监听设备类事件
        FunSupport.getInstance().registerOnFunDeviceListener(this);
        FunSupport.getInstance().registerOnFunDeviceOptListener(this);
        // 刷新设备列表
        refreshLanDeviceList();

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mLanDeviceList.get(i).getDevName() != null){

                    // 设置登录方式为互联网方式
                    FunSupport.getInstance().setLoginType(FunLoginType.LOGIN_BY_INTENTT);

                    // 虚拟一个设备, 只需要序列号和设备类型即可添加
//                    FunDevice d = new FunDevice();
//                    d.devSn = mFunDevice.getDevSn();
//                    d.devName = mFunDevice.getDevName();
//                    d.devMac = mFunDevice.getDevMac();
//                    d.devIp = mFunDevice.getDevIP();
//                    d.devType = FunDevType.EE_DEV_BOUTIQUEROTOT;
//                    d.loginName = "admin";
//                    d.loginPsw = "";

//                    FunDevice d = new FunDevice();
//                    d.devSn = mLanDeviceList.get(i).getDevSn();
//                    d.devName = mLanDeviceList.get(i).getDevName();
//                    d.devType = FunDevType.EE_DEV_BOUTIQUEROTOT;
//                    d.loginName = "admin";
//                    d.loginPsw = "";

                    Log.i("安防摄像头" , "设备登陆成功" + FunSupport.getInstance().getDeviceList().size());
                    // 添加设备之前都必须先登录一下,以防设备密码错误,也是校验其合法性
                    FunSupport.getInstance().requestDeviceLogin(mLanDeviceList.get(i));
                    isAddingDevice = true;
                    showWaitDialog("正在添加中...");

//
                }
            }
        });

        // 打开之后进行一次搜索
        requestToGetLanDeviceList();
    }


    @Override
    protected void onDestroy() {

        // 注销设备事件监听
        FunSupport.getInstance().removeOnFunDeviceListener(this);
        FunSupport.getInstance().removeOnFunDeviceOptListener(this);

        // 切换回网络访问
        FunSupport.getInstance().setLoginType(FunLoginType.LOGIN_BY_INTENTT);

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backBtnInTopLayout: {
                // 返回/退出
                finish();
            }
            break;
            case R.id.btnRefresh: {
                // 刷新设备列表
                requestToGetLanDeviceList();
            }
            break;
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }


    private void requestToGetLanDeviceList() {
        if (!FunSupport.getInstance().requestLanDeviceList()) {
            showToast(R.string.guide_message_error_call);
        } else {
            showWaitDialog();
        }
    }

    private void refreshLanDeviceList() {
        // Demo，如果是进入设备列表就切换到本地模式,退出时切换回NET模式
        FunSupport.getInstance().setLoginType(FunLoginType.LOGIN_BY_LOCAL);

        if (!isAddingDevice) {
            hideWaitDialog();
        }

        mLanDeviceList.clear();

        mLanDeviceList.addAll(FunSupport.getInstance().getLanDeviceList());

        FunDevice f1 = new FunDevice();

        cameraAdapter.refreshData(mLanDeviceList);

        // 延时100毫秒更新设备消息
        mHandler.removeMessages(MESSAGE_REFRESH_DEVICE_STATUS);
        if (mLanDeviceList.size() > 0) {
            mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH_DEVICE_STATUS, 100);
        }
    }


    /**
     * 以下函数实现来自OnFunDeviceListener()，监听设备列表变化
     */
    @Override
    public void onDeviceListChanged() {
    }

    @Override
    public void onDeviceStatusChanged(final FunDevice funDevice) {
        if (null != cameraAdapter) {
            cameraAdapter.refreshData(mLanDeviceList);
        }
    }

    @Override
    public void onDeviceAddedSuccess() {
        showToast("设备完全添加成功");
        isAddingDevice = false;
        hideWaitDialog();
    }


    @Override
    public void onDeviceAddedFailed(Integer errCode) {
        showToast("设备在添加的时候失败了：" +  FunError.getErrorStr(errCode));
        isAddingDevice = false;
        hideWaitDialog();
    }


    @Override
    public void onDeviceRemovedSuccess() {

    }


    @Override
    public void onDeviceRemovedFailed(Integer errCode) {

    }

    @Override
    public void onAPDeviceListChanged() {

    }

    @Override
    public void onLanDeviceListChanged() {
        refreshLanDeviceList();
    }



    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_REFRESH_DEVICE_STATUS: {
                    FunSupport.getInstance().requestAllLanDeviceStatus();
                }
                break;
            }
        }

    };

    private void requestDeviceAdd() {
        if ( null != mFunDevice ) {
            FunSupport.getInstance().requestDeviceAdd(mFunDevice);
        }
    }

    @Override
    public void onDeviceLoginSuccess(FunDevice funDevice) {
        mFunDevice = funDevice;
//        showToast("设备登陆成功");
        Log.i("安防摄像头" , "设备登陆成功" + funDevice.getDevSn() + "---" + funDevice.getDevMac() + "---" + FunSupport.getInstance().getDeviceList().size());

//        requestDeviceAdd();

        JSONObject obj = new JSONObject();
        try {
            obj.put("classification", "1");
            obj.put("hid", DeviceManager.getInstance().hid);
            obj.put("mainDeviceId", "0");
            obj.put("productId", "7");
            obj.put("deviceAddress", funDevice.getDevSn());
            obj.put("deviceModel", "XM-1");
            obj.put("deviceName", funDevice.getDevSn());
            obj.put("deviceType", DeviceType.DEVICE_TYPE_SECURITY_CAMERA + "");
            obj.put("deviceVersion", "1.0");
            obj.put("deviceWifiSSID", getConnectWifiSSID());
            obj.put("deviceId", "0");
            obj.put("key", "10000");
            obj.put("requestTime", "" + System.currentTimeMillis());
            obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
        } catch (JSONException e1) {
            e1.printStackTrace();
        }


        OkHttpUtils.postString().url(HttpURL.UPLOAD_DEVICE_URL)
                .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                .content(obj.toString())
                .build().readTimeOut(5000)
                .writeTimeOut(5000).connTimeOut(5000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        isAddingDevice = false;
                        hideWaitDialog();
                        showToast("添加设备失败");
                    }

                    @Override
                    public void onResponse(String response) {
                        hideWaitDialog();
                        isAddingDevice = false;
//                        finish();
                        Log.i("安防摄像头" , "onSuccess:"+response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String value = jsonObject.getString("resultCode");
                            if (value.equals("1")) {
                                showToast("添加设备成功");
                            }else{
                                showToast("添加设备失败");
                            }
                        } catch (JSONException e) {
                            showToast("数据解析错误");
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public void onDeviceLoginFailed(FunDevice funDevice, Integer errCode) {
        showToast("设备登陆失败:" + FunError.getErrorStr(errCode));
        isAddingDevice = false;
        hideWaitDialog();
    }

    @Override
    public void onDeviceGetConfigSuccess(FunDevice funDevice, String configName, int nSeq) {

    }

    @Override
    public void onDeviceGetConfigFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceSetConfigSuccess(FunDevice funDevice, String configName) {

    }

    @Override
    public void onDeviceSetConfigFailed(FunDevice funDevice, String configName, Integer errCode) {

    }

    @Override
    public void onDeviceChangeInfoSuccess(FunDevice funDevice) {

    }

    @Override
    public void onDeviceChangeInfoFailed(FunDevice funDevice, Integer errCode) {

    }

    @Override
    public void onDeviceOptionSuccess(FunDevice funDevice, String option) {

    }

    @Override
    public void onDeviceOptionFailed(FunDevice funDevice, String option, Integer errCode) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice) {

    }

    @Override
    public void onDeviceFileListChanged(FunDevice funDevice, H264_DVR_FILE_DATA[] datas) {

    }

    @Override
    public void onDeviceFileListGetFailed(FunDevice funDevice) {

    }


    class MyLanCameraAdapter extends BaseAdapter{
        private Context context;
        private List<FunDevice> lanDeviceList;

        public MyLanCameraAdapter(Context context , List<FunDevice> lanDeviceList){
            this.context = context;
            this.lanDeviceList = lanDeviceList;
        }

        public void refreshData(List<FunDevice> data){
            lanDeviceList = data;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return lanDeviceList.size();
        }

        @Override
        public Object getItem(int i) {
            return lanDeviceList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;
            if (view == null){
                view = LayoutInflater.from(context).inflate(R.layout.item_camera_lan , null , false);
                viewHolder = new ViewHolder(view);
                view.setTag(viewHolder);
            }
            if (viewHolder == null){
                viewHolder = (ViewHolder) view.getTag();
            }

            viewHolder.name.setText(lanDeviceList.get(i).getDevName() == null ? "" :  lanDeviceList.get(i).getDevName());
            viewHolder.mac.setText(lanDeviceList.get(i).getDevMac() == null ? "" :  lanDeviceList.get(i).getDevMac());
            viewHolder.sn.setText(lanDeviceList.get(i).getSerialNo() == null ? "" :  lanDeviceList.get(i).getSerialNo());


            return view;
        }

        class ViewHolder {
            TextView name;
            TextView mac;
            TextView sn;
            public ViewHolder(View view){
                 name = (TextView) view.findViewById(R.id.item_tv_device_name);
                 mac = (TextView) view.findViewById(R.id.item_tv_device_mac);
                 sn = (TextView) view.findViewById(R.id.item_tv_device_sn);
            }
        }
    }

    private String getConnectWifiSSID() {
        try {
            WifiManager wifimanage=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            return wifimanage.getConnectionInfo().getSSID().replace("\"", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
